package com.lxm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxm.common.contants.LxmCommentConstants;
import com.lxm.common.tools.ContentUtils;
import com.lxm.common.tools.UserHolder;
import com.lxm.dto.CommentDTO;
import com.lxm.dto.Result;
import com.lxm.entity.LxmComment;
import com.lxm.entity.Login;
import com.lxm.mapper.LxmCommentDao;
import com.lxm.service.LxmCommentService;
import com.lxm.service.LoginService;
import com.lxm.vo.CommentDetailVO;
import com.lxm.vo.CommentPageVO;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-10-02
 */
@Service
public class LxmCommentServiceImpl extends ServiceImpl<LxmCommentDao, LxmComment> implements LxmCommentService {

    @Resource
    private LoginService loginService;

    @Override
    public Result addComment(CommentDTO commentDTO) {
        Long userId = UserHolder.getUser().getUserId();
        LxmComment lxmComment = BeanUtil.copyProperties(commentDTO, LxmComment.class);
        lxmComment.setRemarkerId(userId);
        boolean isSuccess = save(lxmComment);
        return isSuccess ? Result.ok(LxmCommentConstants.COMMENT_SUCCESS)
                : Result.fail(LxmCommentConstants.COMMENT_FAIL);
    }

    @Override
    public Result deleteComment(List<Long> commentIds) {
        if (CollUtil.isEmpty(commentIds)) {
            return Result.fail(LxmCommentConstants.DELETE_COMMENT_EMPTY_FAIL);
        }
        Long userId = UserHolder.getUser().getUserId();
        boolean isRemove = remove(new LambdaQueryWrapper<LxmComment>()
                .eq(LxmComment::getRemarkerId, userId)
                .in(LxmComment::getCommentId, commentIds));
        return isRemove ? Result.ok(LxmCommentConstants.DELETE_COMMENT_SUCCESS)
                : Result.fail(LxmCommentConstants.DELETE_COMMENT_FAIL);
    }

    @Override
    public Result listByUserId(Integer current) {
        Long userId = UserHolder.getUser().getUserId();
        List<LxmComment> lxmCommentList = lambdaQuery()
                .eq(LxmComment::getRemarkerId, userId)
                .orderByDesc(LxmComment::getCreateTime)
                .page(new Page<>(current, LxmCommentConstants.COMMENT_PAGE_SIZE))
                .getRecords();
        //为空之间返回空数组
        if (CollUtil.isEmpty(lxmCommentList)) {
            return Result.ok(lxmCommentList);
        }
        List<CommentPageVO> commentPageVOList = lxmCommentList
                .stream()
                .map(lxmComment -> {
                    CommentPageVO commentPageVO = BeanUtil
                            .toBean(lxmComment, CommentPageVO.class);
                    // 获取评论brief,简写
                    commentPageVO.setUserComment(ContentUtils
                            .getBriefMiddle(commentPageVO.getUserComment()
                                    , LxmCommentConstants.COMMENT_BRIEF_LENGTH));
                    //返回评论的总长度，这里方便前端进行判断，评论是否已经展示完毕
                    commentPageVO.setCommentLength(commentPageVO.getUserComment().length());
                    return commentPageVO;
                })
                .collect(Collectors.toList());
        return Result.ok(commentPageVOList);
    }

    @Override
    public List<CommentDetailVO> getDetailCommentList(Long parentId,
                                                      Integer commentType, Integer current) {
        // 获取评论列表
        List<LxmComment> lxmCommentList = lambdaQuery()
                .eq(LxmComment::getParentId, parentId)
                .eq(LxmComment::getCommentType, commentType)
                .page(new Page<>(current, LxmCommentConstants.COMMENT_PAGE_SIZE))
                .getRecords();
        // 如果为空直接返回空列表
        if (CollUtil.isEmpty(lxmCommentList)) {
            return null;
        }
        // 不为空，将VO封装完毕返回。
        List<CommentDetailVO> commentDetailVOS = lxmCommentList
                .stream()
                .map(this::getCommentDetailVO)
                .collect(Collectors.toList());
        // 返回评论VO列表
        return commentDetailVOS;
    }

    /**
     * 获取评论详情VO,这里面用了递归获取评论的详细信息
     *
     * @param lxmComment 评论实体
     * @return 评论详情VO
     */

    @NotNull
    private CommentDetailVO getCommentDetailVO(LxmComment lxmComment) {
        // 将评论实体转换为VO
        CommentDetailVO commentDetailVO = BeanUtil.toBean(lxmComment, CommentDetailVO.class);
        // 获取评论者信息
        Login userInfo = loginService.getUserInfoLogin(lxmComment.getRemarkerId());
        // 设置评论者信息
        commentDetailVO.setRemarkerName(userInfo.getNickName());
        commentDetailVO.setRemarkerIcon(userInfo.getIcon());
        // 获取回复列表
        List<LxmComment> lxmComments = lambdaQuery()
                .eq(LxmComment::getParentId, commentDetailVO.getCommentId())
                .eq(LxmComment::getCommentType, LxmCommentConstants.COMMENT_TYPE)
                .list();
        // 如果回复列表为空，则直接返回
        if (CollUtil.isEmpty(lxmComments)) {
            commentDetailVO.setReplyList(null);
            return commentDetailVO;
        }
        //不为空,将回复列表转换为VO
        List<CommentDetailVO> commentDetailVOS = lxmComments
                .stream()
                .map(this::getCommentDetailVO)
                .collect(Collectors.toList());
        // 返回子回复列表
        commentDetailVO.setReplyList(commentDetailVOS);
        // 返回VO
        return commentDetailVO;
    }


}
